﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using BEGDC.PreContract.BLL;
using BEGDC.PreContract.BLL.Authentication;
using BEGDC.Utility.Castle;
using PreContractInfo = BEGDC.PreContract.DAL.PreContractInfo;

namespace PreContractWeb.Task
{
    public partial class PreContractList : Page
    {
        private string DataFilter
        {
            get
            {
                if (ViewState["DataFilter"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return (string)ViewState["DataFilter"];
                }
            }
            set
            {
                ViewState["DataFilter"] = value;
            }
        }

        private SortManager SortManager
        {
            get
            {
                if (ViewState["SortManager"] == null)
                {
                    return new SortManager();
                }
                else
                {
                    return (SortManager)ViewState["SortManager"];
                }
            }
            set
            {
                ViewState["SortManager"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.Request.QueryString["Download"] != null)
            {
                btnExport_Click(null, null);
                return;
            }

            #region  Response Write
            Response.Write(@"

                            <style>
                            .table_ajax
                            {
	                            border-top: 1px;
	                            border-top-color:#636363;
	                            border-top-style:solid;
	                            border-bottom: 1px;
	                            border-bottom-color:#636363;
	                            border-bottom-style:solid;
	                            border-left: 1px;
	                            border-left-color:#636363;
	                            border-left-style:solid;
	                            border-right: 1px;
	                            border-right-color:#636363;
	                            border-right-style:solid;
	                            font-family:Arial, Helvetica, sans-serif;
	                            font-size:12px;
	                            color: #636363;
	                            height: 20px;
                            	
                            }
                            </style>
                            <div style=""position: absolute; left: 40%; top: 40%; overflow: hidden; background-color: white;
                            filter: alpha(opacity=50); opacity: 0.5; -moz-opacity: 0.5;"" id=""AJAXProgress"">
                            <table class=""table_ajax"">
                                <tr>
                                    <td style=""width: 35px"">
                                        <img src=""../Images/roller.gif"" /></td>
                                    <td style=""width: 100px"">
                                        Processing...</td>
                                </tr>
                            </table>
                        </div>");
            #endregion

            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));

            if (!Page.IsPostBack)
            {
                Response.Flush();
                //btnAddNew.Visible = false;
                btnSendEmail.Visible = false;
                btnDelete.Visible = false;

                this.CreateGridColumn();

                if (Page.User.IsInRole(Role.EnumRole.Admin.ToString()))
                {
                    //btnAddNew.Visible = true;
                    btnSendEmail.Visible = true;
                    btnDelete.Visible = true;
                }
                else
                {
                    gvMain.Columns[2].Visible = false;
                }

                //if (Page.Request.QueryString["Search"] != null)
                //{
                //    btnAddNew.Visible = false;
                //    if (Page.Request.QueryString["Search"] == "2")
                //    {
                //        btnAddNew.Visible = false;
                //    }
                //}

                //BaseFunction.BindContractStatusDropDownList(ddlContractStatus, string.Empty, true);
                //ddlContractStatus.Items.RemoveAt(3);

                BindGridView();
            }

            if (returnvalue != null && returnvalue.Value != "")
            {
                returnvalue.Value = "";
                BindGridView();
                if (gvMain.PageCount >= pgMain.GVCurrentPageIndex)
                {
                    pgMain.PageChangeEvent();
                }
            }
        }

        #region SearchSQL

        protected string AdjustID
        {
            get
            {
                if (Request.QueryString["AdjustID"] != null)
                {
                    return Request.QueryString["AdjustID"].ToString();
                }
                return string.Empty;
            }
        }

        protected string AdjustDisplayName
        {
            get
            {
                if (Request.QueryString["AdjustDisplayName"] != null)
                {
                    string value = Request.QueryString["AdjustDisplayName"].ToString();
                    return value == "Try" ? "Try&Buy" : value;
                }
                return string.Empty;
            }
        }

        protected string StatusID
        {
            get
            {
                if (Request.QueryString["StatusID"] != null)
                {
                    return Request.QueryString["StatusID"].ToString();
                }
                return string.Empty;
            }
        }

        protected string BDCode
        {
            get
            {
                if (Request.QueryString["BDCode"] != null)
                {
                    return Request.QueryString["BDCode"].ToString();
                }
                return string.Empty;
            }
        }

        protected string BGCode
        {
            get
            {
                if (Request.QueryString["BGCode"] != null)
                {
                    return Request.QueryString["BGCode"].ToString();
                }
                return string.Empty;
            }
        }

        protected string ClusterEName
        {
            get
            {
                if (Request.QueryString["ClusterEName"] != null)
                {
                    return Request.QueryString["ClusterEName"].ToString();
                }
                return string.Empty;
            }
        }

        protected string ProvinceEName
        {
            get
            {
                if (Request.QueryString["ProvinceEName"] != null)
                {
                    return Request.QueryString["ProvinceEName"].ToString();
                }
                return string.Empty;
            }
        }

        protected string CATID
        {
            get
            {
                if (Request.QueryString["CATID"] != null)
                {
                    return Request.QueryString["CATID"].ToString();
                }
                return string.Empty;
            }
        }

        protected string CATCODE
        {
            get
            {
                if (Request.QueryString["CATCODE"] != null)
                {
                    return Request.QueryString["CATCODE"].ToString();
                }
                return string.Empty;
            }
        }

        protected string PromisedDate
        {
            get
            {
                if (Request.QueryString["PromisedDate"] != null)
                {
                    return Request.QueryString["PromisedDate"].ToString();
                }
                return string.Empty;
            }
        }

        protected string SignDue
        {
            get
            {
                if (Request.QueryString["SignDue"] != null)
                {
                    return Request.QueryString["SignDue"].ToString();
                }
                return string.Empty;
            }
        }

        protected string SignActual
        {
            get
            {
                if (Request.QueryString["SignActual"] != null)
                {
                    return Request.QueryString["SignActual"].ToString();
                }
                return string.Empty;
            }
        }

        protected string TradeMonth
        {
            get
            {
                if (Request.QueryString["TradeMonth"] != null)
                {
                    return Request.QueryString["TradeMonth"].ToString();
                }
                return string.Empty;
            }
        }

        protected string ERPReceived
        {
            get
            {
                if (Request.QueryString["ERPReceived"] != null)
                {
                    return Request.QueryString["ERPReceived"].ToString();
                }
                return string.Empty;
            }
        }

        protected string ExistMonth
        {
            get
            {
                if (Request.QueryString["ExistMonth"] != null)
                {
                    return Request.QueryString["ExistMonth"].ToString();
                }
                return string.Empty;
            }
        }

        protected string Delivered
        {
            get
            {
                if (Request.QueryString["Delivered"] != null)
                {
                    return Request.QueryString["Delivered"].ToString();
                }
                return string.Empty;
            }
        }

        protected string DeliveryPercent
        {
            get
            {
                if (Request.QueryString["DeliveryPercent"] != null)
                {
                    return Request.QueryString["DeliveryPercent"].ToString();
                }
                return string.Empty;
            }
        }

        protected string DeliveryPlan
        {
            get
            {
                if (Request.QueryString["DeliveryPlan"] != null)
                {
                    return Request.QueryString["DeliveryPlan"].ToString();
                }
                return string.Empty;
            }
        }

        protected string Aging
        {
            get
            {
                if (Request.QueryString["Aging"] != null)
                {
                    return Request.QueryString["Aging"].ToString();
                }
                return string.Empty;
            }
        }

        protected string Path
        {
            get
            {
                if (Request.QueryString["Path"] != null)
                {
                    return Request.QueryString["Path"].ToString();
                }
                return string.Empty;
            }
        }

        protected string Risk
        {
            get
            {
                if (Request.QueryString["Risk"] != null)
                {
                    return Request.QueryString["Risk"].ToString();
                }
                return string.Empty;
            }
        }

        protected string TryEndDate
        {
            get
            {
                if (Request.QueryString["TryEndDate"] != null)
                {
                    return Request.QueryString["TryEndDate"].ToString();
                }
                return string.Empty;
            }
        }

        #endregion

        private string GetSearchString()
        {
            string strSQL = string.Empty;

            if (!string.IsNullOrEmpty(this.AdjustID))
            {
                strSQL += string.Format(" and AdjustID = {0}", this.AdjustID);
            }

            if (!string.IsNullOrEmpty(this.AdjustDisplayName))
            {
                switch (this.AdjustDisplayName)
                {
                    case "Pre-":
                        strSQL += " and AdjustID = 21";
                        break;
                    case "Test/Lease":
                        strSQL += " and AdjustID in (18,20)";
                        break;
                    case "Try&Buy":
                        strSQL += " and AdjustID = 19";
                        break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(this.StatusID))
            {
                strSQL += string.Format(" and StatusID = {0}", this.StatusID);
            }

            if (!string.IsNullOrEmpty(this.BDCode))
            {
                strSQL += string.Format(" and BDCode = N'{0}'", this.BDCode);
            }

            if (!string.IsNullOrEmpty(this.BGCode))
            {
                //strSQL += string.Format(" and BGCode = N'{0}'", this.BGCode);
                strSQL += string.Format(" and BGCode = N'{0}' and BDActive = 1", this.BGCode);
            }

            if (!string.IsNullOrEmpty(this.ClusterEName))
            {
                strSQL += string.Format(" and ClusterEName = N'{0}'", this.ClusterEName);
            }

            if (!string.IsNullOrEmpty(this.ProvinceEName))
            {
                strSQL += string.Format(" and ProvinceEName = N'{0}'", this.ProvinceEName);
            }

            if (!string.IsNullOrEmpty(this.CATID))
            {
                strSQL += string.Format(" and CATID = {0}", this.CATID);
            }

            if (!string.IsNullOrEmpty(this.CATCODE))
            {
                strSQL += string.Format(" and CATCode = N'{0}'", this.CATCODE);
            }

            if (!string.IsNullOrEmpty(this.PromisedDate))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.SignDue))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.SignActual))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.TradeMonth))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.ERPReceived))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.ExistMonth))
            {
                strSQL += string.Format(" and ExistMonth = {0}", this.ExistMonth);
            }

            if (!string.IsNullOrEmpty(this.Delivered))
            {
                strSQL += string.Format(" and Delivered = {0}", this.Delivered);
            }

            if (!string.IsNullOrEmpty(this.DeliveryPercent))
            {
                strSQL += "";
            }

            if (!string.IsNullOrEmpty(this.DeliveryPlan))
            {
                strSQL += string.Format(" and DeliveryPlan = N'{0}'", this.DeliveryPlan);
            }

            if (!string.IsNullOrEmpty(this.Aging))
            {
                switch (this.Aging)
                {
                    case "<1":
                        strSQL += " and ExistMonth < 1";
                        break;
                    case "1-3":
                        strSQL += " and ExistMonth in (1,2,3)";
                        break;
                    case "2-6":
                        strSQL += " and ExistMonth in (4,5,6)";
                        break;
                    case "7-9":
                        strSQL += " and ExistMonth in (7,8,9)";
                        break;
                    case "10-12":
                        strSQL += " and ExistMonth in (10,11,12)";
                        break;
                    case ">12":
                        strSQL += " and ExistMonth > 12";
                        break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(this.Risk))
            {
                strSQL += string.Format(" and IsRisk = {0}", this.Risk);
            }

            if (!string.IsNullOrEmpty(this.TryEndDate))
            {
                strSQL += "";
            }

            //
            //strSQL += " and CATActive = 1";

            //strSQL += " and AdjustID is not null";
            if (!strSQL.Contains("AdjustID"))
            {
                strSQL += " and AdjustID is not null";
            }

            return strSQL;
        }

        public void BindGridView()
        {
            try
            {
                string strpermission = ((PCPrincipal)Page.User).DataPermission;
                strpermission += string.IsNullOrEmpty(strpermission) ? " 1=1 " + GetSearchString() : GetSearchString();

                IPreContractInfo contractservice = (IPreContractInfo)AppContainer.Instance[Services.CONST_PreContractInfo_Service];
                DataTable dt = contractservice.GetPreContractInfo(strpermission);
                dt.DefaultView.Sort = SortManager.ToString();
                dt.DefaultView.RowFilter = DataFilter;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["DelayWeeks"].ToString()) < 0)
                        dt.Rows[i]["DelayWeeks"] = 0;
                }

                gvMain.DataSource = dt.DefaultView;
                gvMain.DataBind();

                totalSpan.InnerText = dt.DefaultView.Count.ToString();

                this.pgMain.Visible = true;
                this.pgMain.BindtoGridView(this.gvMain, dt.DefaultView);
                if (this.gvMain.Rows.Count == 0)
                {
                    this.pgMain.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                e.Row.Cells[3].Text = "<a onclick=\"javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "');\">" + e.Row.Cells[1].Text.Trim() + "</a>";
                e.Row.Cells[0].ID = "PreContractID";
                e.Row.Cells[1].ID = "PreContractNo";
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = ((DataRowView)e.Row.DataItem);
                if (Convert.ToInt32(drv.Row[PreContractInfo.CONST_StatusID]) == (int)DicItem.PreContractStatus.Won)
                {
                    e.Row.CssClass = "table_row_3";
                }
                e.Row.Cells[e.Row.Cells.Count - 1].Text = e.Row.Cells[e.Row.Cells.Count - 1].Text.Replace("/", "-");
                if (!string.IsNullOrEmpty(this.lblSpecialApprove.Text))
                {
                    int index = Convert.ToInt32(this.lblSpecialApprove.Text);
                    if (index >= 4)
                    {
                        e.Row.Cells[index].Text = e.Row.Cells[index].Text.Replace("1", "正常终审-").Replace("2", "PCAT承诺ValueLine-").Replace("3", "转正时间长或不确定-").Replace("4", "PSO/CAT邮件承诺ValueLine-").Replace("|||", "").TrimEnd(Convert.ToChar("-"));
                    }
                }
            }
        }

        protected void gvMain_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.pgMain.GVCurrentPageIndex = 1;
            SortManager sort = SortManager;
            sort.DoSort(e.SortExpression);
            SortManager = sort;
            BindGridView();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        private bool IsCFIRole()
        {
            int EemployeeId = ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId;
            BEGDC.PreContract.BLL.IUserRole iUserRole = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];
            DataTable dtEmpRole = iUserRole.GetUserRole_DataTable(String.Format("EmployeeID = {0}", EemployeeId));
            BEGDC.PreContract.DAL.Role role = new BEGDC.PreContract.DAL.Role();
            BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];

            bool isCFIRole = false;
            for (int t = 0; t < dtEmpRole.Rows.Count; t++)
            {
                role = iRole.GetRole(Convert.ToInt32(dtEmpRole.Rows[t]["RoleID"].ToString()));
                if (role.Description.Contains("CFI"))
                {
                    isCFIRole = true;
                    break;
                }
            }
            return isCFIRole;
        }

        /// <summary>
        /// Create GridView Columns
        /// </summary>
        private void CreateGridColumn()
        {
            string filter = string.Format("DicTypeID = {0} and IsEnabled = 1", BaseFunction.CONST_PRECONTRACT_COLUMNS_DICTYPE);
            IDicItem iDicItem = (IDicItem)AppContainer.Instance[Services.CONST_DicItem_Service];
            DataTable dt = iDicItem.GetDicItem_DataTable(filter);

            int index = 0;
            bool isCFIRole = this.IsCFIRole();

            foreach (DataRow row in dt.Rows)
            {
                BoundField newCol = new BoundField();
                newCol.HeaderText = row["DicItemDesc"].ToString().Replace("-", "\n");
                newCol.DataField = row["DicItemValue"].ToString();
                newCol.SortExpression = row["DicItemValue"].ToString();
                newCol.HtmlEncode = false;
                newCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

                if (isCFIRole == false && newCol.DataField == PreContracColumn.CFIPrice)
                    continue;

                if (newCol.DataField == PreContracColumn.SignActual
                    || newCol.DataField == PreContracColumn.PromisedDate
                    || newCol.DataField == PreContracColumn.SignDue
                    || newCol.DataField == PreContracColumn.ERPReceived
                    || newCol.DataField == PreContracColumn.DeliveryDate
                    || newCol.DataField == PreContracColumn.AOGDate
                    || newCol.DataField == PreContracColumn.BlackDate
                    || newCol.DataField == PreContracColumn.CommentPromisedDate)
                {
                    newCol.DataFormatString = "{0:yyyy-MM-dd}";
                }

                if (newCol.DataField == PreContracColumn.SparePrice
                     || newCol.DataField == PreContracColumn.OrionPrice
                     || newCol.DataField == PreContracColumn.CEWPromised
                     || newCol.DataField == PreContracColumn.SalePrice
                     || newCol.DataField == PreContracColumn.CFIPrice
                     || newCol.DataField == PreContracColumn.DeliveryPercent)
                {
                    newCol.DataFormatString = "{0:N2}";
                }

                if (newCol.DataField == PreContracColumn.CEWME
                    || newCol.DataField == PreContracColumn.OrionME
                    || newCol.DataField == PreContracColumn.GAP)
                {
                    newCol.DataFormatString = "{0:N4}";
                }

                if (newCol.DataField == PreContracColumn.Delivered)
                {
                    this.lblDeliveredIndex.Text = (index + 4).ToString();
                }

                if (newCol.DataField == PreContracColumn.SpecialApprove)
                {
                    this.lblSpecialApprove.Text = (index + 4).ToString();
                }

                this.gvMain.Columns.Add(newCol);
                index++;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvMain.Rows.Count; i++)
            {
                CheckBox ck = gvMain.Rows[i].FindControl("chkSelect") as CheckBox;

                if (ck.Checked)
                {
                    string precontractId = gvMain.Rows[i].Cells[0].Text;
                    PreContractInfo precontract = new PreContractInfo();
                    precontract.PreContractID = Convert.ToInt32(precontractId);
                    precontract.Delete();
                }
            }

            this.pgMain.GVCurrentPageIndex = 1;
            BindGridView();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            gvMain.AllowSorting = false;

            if (this.IsCFIRole() == false && !string.IsNullOrEmpty(this.lblDeliveredIndex.Text))
            {
                int index = Convert.ToInt32(this.lblDeliveredIndex.Text);
                if (index >= 4)
                {
                    gvMain.Columns.RemoveAt(index);
                }
            }

            this.gvMain.PageSize = Convert.ToInt32(this.totalSpan.InnerText);
            BindGridView();

            DataView dt = (DataView)gvMain.DataSource;

            if (dt.Count >= 1)
            {
                BaseFunction.ExportToExcel(Page, gvMain, "Pre-ContractList.xls");
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('没有查询结果导出！\nNo data to be exported');</script>");
            }
        }
    }
}
